

$(function(){
  
  $('#btn-scan-imte').on('click',function(){
    $('#scan_modal').modal('toggle')
    instascan()
  })
  var deleteConfirm = new Confirm({
    body: "Type <strong>\"DELETE\"</strong> to delete the form.",
    type:'prompt'
  })
  
  var doneConfirm = new Confirm({
    body:"Are you confirm to change the state of the form to DONE?"
  })

  const socket = io.connect(`${OCR_DECTECTION_IP}:5000`)
  const psu_current = $('#psu-current')
  const psu_voltage = $('#psu-voltage')
  const meter = $('#meter')
  let fetchReading = _=>setInterval(_=>{
    socket.emit('DetectionValues',data=>{
      psu_v = data.psu.split(';')
      console.log(psu_v)
      psu_current.html(psu_v[0])
      psu_voltage.html(psu_v[1])
      meter.html(data.meter)
    })
  },300)
  socket.on('connect',_=>{
    fetchReading()
  })
  Formio.icons = 'fontawesome';
  Formio.createForm(document.getElementById('formio'), 
      dataJson
  ).then(function(form) {
      var is_zoom = false
      var last_scroll_pos = 0
      function trigger_zoom(){

        return  new Promise((resolve,reject)=>{
          if (!is_zoom){
            last_scroll_pos = $(window).scrollTop()
            $('#zoom-fa').removeClass("fa-search-minus")
            $('#zoom-fa').addClass("fa-search-plus")
            $('#eform_container').css("zoom","33%")
            $('#eform_container').css("padding-left","33%")
            $('#eform_container').css("padding-right","33%")
            $(window).scrollTop($("#eform_container").offset().top)
          }else{
            $('#zoom-fa').removeClass("fa-search-plus")
            $('#zoom-fa').addClass("fa-search-minus")
            $('#eform_container').css("zoom","100%")
            $('#eform_container').css("padding-left","")
            $('#eform_container').css("padding-right","")
          }
          is_zoom = !is_zoom
          
          resolve(!is_zoom)
        });
      } 
      $('#btn-zoom').on('click',function(){
        trigger_zoom().then(is_zoom=>{
          if (is_zoom){
            $(window).scrollTop(last_scroll_pos)
          }
        })
        // is_zoom = !is_zoom
      })

      $('input, textarea , .form-control, .input-group').on('click',function(e){
        if (is_zoom){
          trigger_zoom().then(iz=>{
              $('html').animate(
                {
                  scrollTop: $(this).offset().top * 0.8
                },
                800 
              );
              $(this).focus()
          })
        }
      })
      
      form.submission  = {
        data:data
      }
      
      
      // // console.log(form._data)
      // $('#log-data').on('click',function(e){
        
      //   console.log(form.submission)
      //   form.validator.validate()
      //   coms = form.components
      //   for (let index = 0; index < coms.length; index++) {
      //     const com = coms[index];
      //     if (com.validator.validate() == false){
      //       com.scrollIntoView()
      //       com.focus()
      //     }
      //   }
      //   // console.log(form)
      // })

      $('.c-btn-s').on('click',function(e){
        var action = $(this).val()
        var dataJson_str = JSON.stringify(form._data)
        console.log(dataJson_str)
        $('#dataJson').val(dataJson_str)
        if (action == 'done'){
          doneConfirm.show(()=>{
            // check formio
            if(form.checkValidity(null,true)==false){
              // scroll to invalid
              // invalid = $('.is-invalid')[0]
              invalids = $('.is-invalid')
              for (let invalid of invalids){
                const hasSoft = invalid.closest('.soft-validate')
                console.log('hasSoft', hasSoft);
                if (invalid && hasSoft==null){
                  invalid.focus()
                  return
                }
              }
              // let hasSoft =  $('.is-invalid').parents('.soft-validate')
            }
            // console.log('isInvalid', isInvalid);
            // if (isInvalid) return
            // console.log('hasSoft', hasSoft);
            // if(!form.checkValidity()){
            //   setTimeout(_=>form.reportValidity(),100)
            // }
            // return
            // check submit form
            let fm = document.getElementById('eform')
            if (!fm.checkValidity()){
              setTimeout(_=>fm.reportValidity(),100)
              return
            }
            console.log('continue...');
            $('#dataAction').val(action)
            $('#overall_test_result').val($('input[name="overall_test_result_radio"]:checked').val())
            $('#eform').trigger('submit')
          },(bo)=>{
            return bo
          })
        }else{
          $('#dataAction').val(action)
          $('#overall_test_result').val($('input[name="overall_test_result_radio"]:checked').val())
          $('#eform').trigger('submit')
        }
      })

      

      $('button[type="submit"]').on('click',function(e){
        console.log(form.schema)
        e.preventDefault()
      })

      

      $('#btn-delete').on('click',_=>{
        console.log('new call back')
        deleteConfirm.show(function(b,p){
          console.log('new call back')
          if (p=='DELETE'){
            // $('#dataJson').val(dataJson_str)
            $('#dataAction').val('delete')
            
            $('#eform').trigger('submit')
          }
        })
        // delete_str = prompt('Type DELETE to delete the form !')
        // if (delete_str == 'DELETE'){
        //   dataJson_str = JSON.stringify(form._data)
        //   console.log(dataJson_str)
        
        // }

      })


      let focused = false;
      $('input').on('focus',function(){
        focused = $(this)
        
      })
      $('.ims-capture').on('click',function(e){
        console.log($(document.activeElement))
        captureValue  = $(this).html().trim()
        if (focused.is('[readonly]') || focused.hasClass("wo-fields")){
          alert("Field is readonly")
          return
        }
        
        // focused.val(captureValue)
        // focused.trigger('change')
        form.getComponent(focused.attr('name').match(/data\[([^)]+)\]/)[1]).setValue(captureValue);

        key = focused.attr('id').split('-').pop()
        if (form._data.hasOwnProperty(key)){
          form._data[key] = captureValue 
        }
      })
  });

})
